package com.ajmd.onlineexam.service;

import com.ajmd.onlineexam.entity.SearchParam;
import com.ajmd.onlineexam.entity.StudentPO;
import com.ajmd.onlineexam.entity.TeacherPO;
import com.ajmd.onlineexam.mapper.TeacherMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ajmd
 * @since 2023/3/30 20:03
 */
@Service
public class TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    public TeacherPO findTeacherById(String account){
        return teacherMapper.selectById(account);
    }

    public int teacherRegister(TeacherPO teacher){
        return teacherMapper.insert(teacher);
    }

    public Page<TeacherPO> findAllStudent(Integer currentPage, Integer pageSize, SearchParam searchParam){
        LambdaQueryWrapper<TeacherPO> queryWrapper = new LambdaQueryWrapper<>();
        if(ObjectUtils.isNotEmpty(searchParam.getSearchValue())){
            queryWrapper.eq(TeacherPO::getName,searchParam.getSearchValue());
        }
        queryWrapper.orderByAsc(TeacherPO::getAccount);
        Page<TeacherPO> page = new Page<>(currentPage, pageSize);
        return teacherMapper.selectPage(page, queryWrapper);
    }

    public int teacherUpdate(TeacherPO teacher){
        UpdateWrapper<TeacherPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("account",teacher.getAccount());
        return teacherMapper.update(teacher,updateWrapper);
    }

    //重置密码
    public int resetPassword(String account){
        LambdaUpdateWrapper<TeacherPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeacherPO::getAccount,account)
                .set(TeacherPO::getPassword, DigestUtils.md5Hex(account));
        return teacherMapper.update(null,updateWrapper);
    }

    //删除教师
    public int delete(String account){
        return teacherMapper.deleteById(account);
    }
}
